package main

// #cgo CFLAGS: -I/opt/homebrew/include
// #cgo LDFLAGS: -L/opt/homebrew/lib -lpcre2-8
// #include "mypcre2.h"
// #include <stdlib.h>
import "C"
import (
	"reflect"
	"unsafe"
)

func cgo_preg_match(pattern, subject string) (results []string) {
	var matches **C.char
	rc := C.preg_match(C.CString(pattern), C.CString(subject), &matches)
	defer C.free(unsafe.Pointer(matches))
	/* ??
	for i := 0; i < int(rc); i++ {
		offset := uintptr(unsafe.Pointer(matches)) + uintptr(i)*unsafe.Sizeof(uintptr(0))
		results = append(results, C.GoString((*C.char)(unsafe.Pointer(offset))))
	}
	*/

	var pbuf []*C.char
	header := (*reflect.SliceHeader)(unsafe.Pointer(&pbuf))
	header.Cap = int(rc)
	header.Len = int(rc)
	header.Data = uintptr(unsafe.Pointer(matches))
	for _, i := range pbuf {
		results = append(results, C.GoString(i))
	}

	return
}
